#!/usr/bin/env bash
. pkg.sh
. cfg.sh
. log.sh
. mod.sh

case $1 in
	config)
		if [ $# -eq 1 ]; then
			set -- config path hook
		fi
		while [ $# -gt 1 ]; do
			case ${2} in
				path)
					while read -r line; do
						echo $line
					done < <(grep -v "^#" paths.conf)
					;;
				hook)
					while read -r line; do
						echo $line
					done < <(grep -v "^#" hooks.conf)
					;;
			esac
			shift
		done
	;;
	auto)
		p=$(readlink -f $0)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if ! [ -d ${TREE_STUMP} ]; then
			$p init
			$p update db
		fi
		$p update conf
		if [ -z "$(ps -ef | grep 'job hook' | grep -v 'grep')" ]; then
			$p hook
		fi
	;;
	update)
		case "${2}" in
			db)
				_log info 'Updating database...'
				store_db
				update_db
				;;
			conf)
				_log info 'Updating config...'
				update_conf
				;;
		esac
	;;
	download)
		shift
		while [ $# -gt 0 ]; do
			D=""
			for i in ${@}; do
				shift
				D="${D} $(depends_pkg ${i})"
				! [ -z ${D} ] && _log info "${i} depends \x1b[1m${D}\x1b[m"
				P="$(lookup_pkg ${i})"
				if [ $? -ne 0 ]; then
					_log error "could not resolve: ${i}"
				else
					download_pkg ${P}
					[ $? -eq 0 ] && prepare_pkg $(echo ${P} | cut -s -f2 -d' ')
				fi
			done
			set -- ${D}
		done
	;;
	list)
		shift
		FILTER="${1}"
		while read -r line; do
			OUT=""
			set -- ${line}
			while [ $# -gt 0 ]; do
				case $(echo "${1}" | grep -oE "${FILTER}|--")  in
					'NEW')
						OUT="\x1b[32mN\x1b[00m  "
						;;
					'MOD')
						OUT=" \x1b[33mC\x1b[00m "
						;;
					'DEL')
						OUT="  \x1b[31mD\x1b[00m"
						;;
					'--')
						[ -z "${OUT}" ] && { shift; continue; }
						DIFF=$(expr 6 - $(echo ${OUT} | wc --bytes))
						printf '[%*b] %s\n' "${DIFF}" "${OUT}" "$(echo ${line} | cut -s -f3- -d'-')"
						;;
				esac
				
				shift
			done
		done < <(diff_db)
	;;
	hook)
		EVENT_FILE=$(grep ^EVENT_FILE ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if ! [ -z "${2}" ]; then

			while read -r line; do
				run_pkg $line $(date --rfc-3339=seconds | tr ' ' '_')
			done < <(grep "${2}" ./hooks.conf | cut -f2- -d' ')
			
			if ! [ "${2}" = "exit" ]; then
				$(readlink -f $0) hook
			fi
		else
			if [ $(stat -t ${EVENT_FILE} | cut -f2 -d' ') -ne 0 ]; then
				$(readlink -f $0) hook "$(sed -i -e '1{w /dev/stdout' -e 'd}' ${EVENT_FILE})";
			else
				{ watch -g stat ${EVENT_FILE} > /dev/null && { $(readlink -f $0) hook "$(sed -i -e '1{w /dev/stdout' -e 'd}' ${EVENT_FILE})"; };} &
			fi
		fi
	;;
	event)
		EVENT_FILE=$(grep ^EVENT_FILE ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if [ -z "${2}" ]; then
			touch ${EVENT_FILE}
		else
			echo "${2}" >> ${EVENT_FILE}
		fi
	;;
	init)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		if [ -d ${TREE_STUMP} ]; then
			_log error 'Already initialized'
			exit 1
		fi
		while read -r line; do
			line=$(echo ${line} | cut -f2 -d'=' | sed 's/^"//;s/"$//')
			if [ "$(echo $line | cut -c1)" = "#" ]; then
				MODE="$(echo $line | cut -c2-)"
				continue
			fi

			
			case "${MODE}" in
				FOLDER)
					DIR=$(eval "echo ${line}")
					mkdir -p ${DIR} 2>&1 > /dev/null
				;;
				FILE)
					DIR=$(eval "echo ${line}")
					# TODO: Create file path?
					touch ${DIR} 2>&1 > /dev/null
				;;
				URL)
					break
				;;
			esac
			case $(ls -ld ${DIR} | cut -c1) in
				d)
					type=DIRECTORY
					;;
				-)
					type=FILE
					;;
			esac
			if [ $? -ne 0 ]; then
				_log error "cannot create ${type} ${DIR}" 2>/dev/null
			else
				_log success "created ${type} ${DIR}"
			fi
		done < paths.conf
	;;
	list)
		exit
		shift
		FMT="%10s %10 %20s\n"
		printf "${FMT}" "NAME" "REPO" "DEPENDS"
		while read -r repo; do
			while read -r line; do
				printf "${FMT}" $(basename ${repo}) ${line}
			done < ${repo}
		done < <(find ${REPO_STORE} -type f)
	;;
	deinit)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		echo ${TREE_STUMP}
		if ! [ -d ${TREE_STUMP} ]; then
			_log error "Not initialized."
			exit
		fi
		START=""
		DELFILES=$(mktemp)
		while read -r line; do
			line=$(readlink -f ${line})
			if [ $(echo ${START} | wc --bytes) -lt $(echo ${line} | wc --bytes) ]; then
				START=${line}
			fi
		done < <(find ${TREE_STUMP})
		[ -f "${START}" ] && START=$(dirname ${START})

		while true; do
			while read -r l; do
#				_log warn "deleting ${l}"
#				rm -rf ${l}
				if [ -z "$(grep -E ^${l}\$ ${DELFILES})" ]; then
					echo ${l} >> ${DELFILES}
				fi
			done < <(find ${START} -type d)
			START=$(dirname ${START})

			if [ ${START} = $(readlink -f ${TREE_STUMP}) ]; then
				break
			fi
		done
		while read -r l; do
#			_log warn "deleting ${l}"
#			rm -rf ${l}
			if [ -z "$(grep -E ^${l}\$ ${DELFILES})" ]; then
				echo ${l} >> ${DELFILES}
			fi
		done < <(find ${START} -type d | sort -r)
		while read -r line; do
#			_log warn "deleting ${line}"
			if [ -z "$(grep ${line} ${DELFILES})" ]; then
				echo ${line} >> ${DELFILES}
			fi
		done < <(sed -n '/^#FILE/,/^#URL/{/^#URL/d; /^#FILE/d; s/^.*="//; s/"$//p}' ./paths.conf)
		_log info 'The following files are going to be deleted:'
		while read -r line; do
			_log info $line
		done < ${DELFILES}
		printf 'Are you okay with this [\x1b[32;1my\x1b[m/\x1b[31;1mN\x1b[m]: '
		read response
		case $(echo $response | tr '[[:lower:]]' '[[:upper:]]') in
			Y*)
				while read -r line; do
					_log success "deleting ${line}"
					rm -rf $line
				done < ${DELFILES}
				
				;;
		esac
		rm ${DELFILES}
	;;
	show)
		TREE_STUMP=$(grep ^TREE_STUMP ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		eval "LOG_STORE="$(grep ^LOG_STORE ./paths.conf | cut -f2 -d'=' | sed 's/^"//;s/"$//')
		RUN=""
		while read -r line; do
			if ! [ -z $(basename $line | grep -E "${2}.*") ]; then
				RUN="${RUN} $(basename $line)"
			fi
		done < <(find ${LOG_STORE} -maxdepth 1 -mindepth 1| sort)
		case $(echo "$RUN" | wc --words) in
			0)
				_log error 'no log matches'
				exit 1
				;;
			1)
				_log success "matched:\x1b[1m${RUN}\x1b[m"
				RUN=$(echo ${RUN} | cut -f1 -d' ')
				;;
			*)
				_log error 'multiple matches!'
				exit 1
				;;
		esac

		TIME=""
		ANSI=""
		MACRO=0
		while read -r line; do
			if [ $(head -1 $line) = ".macros" ]; then
				MACRO=1
			fi
			while read -r l; do
				if [ $MACRO -eq 1 ] && [ $(echo $l | cut -c1) = "." ]; then
					case $(echo $l | cut -c2- | cut -f1 -d' ') in
						type)
							case $(echo ${l} | cut -s -f2 -d' ') in
								error)
									ANSI='\x1b[1;31;7m'
								;;
								*)
									ANSI='\x1b[m'
								;;
							esac
						;;
						reset)
							ANSI='\x1b[m'
						;;
						time)
							TIME=$(date --date="@$(echo ${l} | cut -f2 -d' ')")
						;;
					esac
				else
					if [ $MACRO -eq 1 ]; then
						printf "[%s]: %b%s\x1b[m\n" "${TIME}" "${ANSI}" "$l"
					else
						printf "%s\n" "$l"
					fi
				fi
			done < <(cat $line)
		done < <(find ${LOG_STORE}/${RUN} -mindepth 1 ! -iname 'kickoff')
	;;
esac
